<script>
/**
 * Copyright (C) 2024
 * All rights reserved, Designed By www.joolun.com
 * 注意：
 * 本软件为www.joolun.com开发研制，未经购买不得使用
 * 购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
 * 一经发现盗用、分享等行为，将追究法律责任，后果自负
 */
import service from '@/store/service';
import { showChatNotice } from '@/components/notice/notice-plus-show.js';
import api from '@/api/api';
import __config from '@/config/env';
import JimUtil from '@/utils/jim-util'; // IM工具库
// #ifdef APP-PLUS
import APPUpdate from '@/public/APPUpdate/index.js'; //App版本更新
// #endif

export default {
	globalData: {
		username: null,
		user_id: null,
		tenant_id: null,
		access_token: null,
		expires_in: null, //过期时间：该时间为当前时间之后的时间，单位为毫秒数
		permissions: {}, //权限 Object
		bgColor: 'bg-white', //主题色 参考colorUI支持的class
		JIM: null, //IMJMessage
		IMdata: {
			IMOpenLog: false, //im日志打印
			IMplatform: '5',
			IMoperationID: '',
			IMuserID: '',
			IMtoken: '',
			IMJSwsAddr: '', //wss连接地址
			IMloginStatus: false,
			IMconnectStatus: 0, // 服务器连接状态:0,:失败;1:成功;2:连接中
			IMmessageList: [], // 会话列表
			IMheartCheckTimer: null,
			IMcheckIMLoginOK: false
		},
		isDev: false, // 是否是开发模式,开发模式下会记录日志等显示开发模式下的操作及显示
		showApp: false // app是否打开状态
	},
	data() {
		return {
			refreshTime: null,
			refreshLock: false
		};
	},
	onLaunch() {
		try {
			// service.saveLogInfo("********************** App启动 ************************")
			// 版本更新检测
			// #ifdef APP-PLUS
			APPUpdate();
			// 初始化个推
			this.initUniCid();
			// #endif
			// 判断登录
			service.saveLogInfo(this.$t('joolun-pro-app.app.3a167p'));
			this.startLogin();
			service.saveLogInfo(this.$t('joolun-pro-app.app.b73e56'));
			// 初始化国际化语言
			this.initI18n();
		} catch (e) {
			//TODO handle the exception
			console.log(e);
		}
	},
	onShow: function () {
		console.log('App Show');
		// 初始化OpenIM
		if (this.globalData.JIM) {
			JimUtil.showAPP();
		}
		this.globalData.showApp = true;
		// #ifdef APP-PLUS
		plus.push.clear();
		// #endif
	},
	onHide: function () {
		console.log('App Hide');
		if (this.globalData.JIM) {
			JimUtil.hideAPP();
		}
		this.globalData.showApp = false;
	},
	methods: {
		startLogin() {
			// 登录流程--接口调用处也会判断和验证token
			// 1.如果有值就表示登录过，启动自动登录
			// 		1.1 验证token有效期(一般为7天),如果在有效期内就直接跳转到首页
			// 		1.2 如果token过期,那么就调用刷新token的接口刷新有效期
			// 		1.3 如果refresh_token(一般为30天)也过期那么就跳转到登录页面
			// 2.如果没有登录过就直接跳转到登录页面
			const loginTokenInfo = service.getLoginAccessToken();
			if (loginTokenInfo && loginTokenInfo.access_token) {
				service.saveLogInfo(this.$t('joolun-pro-app.app.51s25t'));
				let curDateTime = new Date().getTime();
				if (curDateTime < loginTokenInfo.expires_in) {
					// 1.1
					service.saveLogInfo(this.$t('joolun-pro-app.app.87qb47'));
					this.globalData.access_token = loginTokenInfo.access_token;
					this.globalData.username = loginTokenInfo.username;
					this.globalData.user_id = loginTokenInfo.user_id;
					this.globalData.tenant_id = loginTokenInfo.tenant_id;
					this.globalData.expires_in = loginTokenInfo.expires_in;
					// 获取个人信息
					this.getUserInfo();
				} else {
					//1.2
					service.saveLogInfo(this.$t('joolun-pro-app.app.6s5cd5'));
					// token过期，刷新token
					api.login
						.refreshToken(loginTokenInfo.refresh_token)
						.then((response) => {
							service.saveLogInfo(this.$t('joolun-pro-app.app.33itp3'));
							// 登录成功 保存登录数据、本次登录的token
							service.saveAccessToken(response, this.globalData);
							// 获取个人信息
							this.getUserInfo();
						})
						.catch((response) => {
							//失败 重新登录
							this.loginFail();
						});
				}
			} else {
				// 登录
				uni.reLaunch({
					url: '/pages/login/login'
				});
			}
		},
		loginFail() {
			service.removeUser();
			uni.showToast({
				icon: 'none',
				position: 'bottom',
				title: this.$t('joolun-pro-app.app.716403')
			});
			uni.reLaunch({
				url: '/pages/login/login'
			});
		},
		getUserInfo() {
			service.saveLogInfo(this.$t('joolun-pro-app.app.4329jf'));
			api.getUserInfo()
				.then((response) => {
					service.saveLogInfo(this.$t('joolun-pro-app.app.f2596g'));
					// 更新用户信息
					service.saveUserInfo(response.data.sysUser);
					// 保存用户权限
					service.saveUserPermissions(response.data.permissions, this.globalData);

					service.saveLogInfo(this.$t('joolun-pro-app.app.l33fej'));
					// 初始化IM
					this.initJIM();
					service.saveLogInfo(this.$t('joolun-pro-app.app.21c42o'));
					service.saveLogInfo(this.$t('joolun-pro-app.app.xi673n'));
					// 初始化个推
					this.initUniCid();
					service.saveLogInfo(this.$t('joolun-pro-app.app.8t1176'));
				})
				.catch((response) => {
					//失败 重新登录
					service.saveLogInfo(this.$t('joolun-pro-app.app.dwpz63') + JSON.stringify(response));
					this.loginFail();
				});
		},
		//初始化OpenIM
		initJIM() {
			let that = this;
			return new Promise((resolve, reject) => {
				//获取用户信息
				let userInfo = service.getUser();
				//还不是商城用户，不登录JLIM
				if (!userInfo || !userInfo.id) {
					console.log(this.$t('joolun-pro-app.app.ssr8tk'));
					resolve('success');
					return;
				}
				if (this.globalData.JIM && this.globalData.IMdata && this.globalData.IMdata.IMloginStatus && this.globalData.IMdata.IMconnectStatus == 1) {
					//OpenIM已经初始化，直接登录
					if (this.globalData.IMdata.IMOpenLog) console.log(this.$t('joolun-pro-app.app.d10u6e'));
					JimUtil.checkLoginStatus();
					//更新一下im个人资料
					JimUtil.updateIMuserInfo(userInfo);
					resolve('success');
					return;
				} else {
					// 初始化
					JimUtil.initOpenIM()
						.then(() => {
							//更新一下im个人资料
							JimUtil.updateIMuserInfo(userInfo);
							resolve('success');
						})
						.catch(() => {
							resolve('success');
						});
				}
			});
		},
		getuiAliasBind() {
			// 绑定个推别名
			service.saveLogInfo('-----bindGetui-----');
			service.saveLogInfo('gettuicid:' + this.globalData.uniAppClientId);
			// console.log("gettuicid:" + this.globalData.uniAppClientId)
			if (this.globalData.uniAppClientId) {
				let userInfo = service.getUser();
				//还不是商城用户，不调用接口
				if (userInfo && userInfo.id) {
					api.mall
						.getuiAliasGet(this.globalData.uniAppClientId)
						.then((res) => {
							// 返回错误码说明 https://docs.getui.com/getui/server/rest_v2/code/
							if (res.code == 20001) {
								service.saveLogInfo('getuiAliasGet:20001');
								let params = {
									dataList: [
										{
											cid: this.globalData.uniAppClientId,
											alias: JimUtil.GetIMuserID()
										}
									]
								};
								api.mall.getuiAliasBind(params).then((res) => {
									if (res.code == 20001) {
										console.log(this.$t('joolun-pro-app.app.u2874c'));
									}
									console.log('getuiAliasBind:' + res.code);
								});
							} else {
								// 别名与cid不一致时进行绑定操作
								if (res.data.alias != JimUtil.GetIMuserID()) {
									let params = {
										dataList: [
											{
												cid: this.globalData.uniAppClientId,
												alias: JimUtil.GetIMuserID()
											}
										]
									};
									api.mall.getuiAliasBind(params).then((res) => {
										if (res.code == 20001) {
											console.log(this.$t('joolun-pro-app.app.u2874c'));
										}
										console.log('getuiAliasBind:' + res.code);
									});
								}
								service.saveLogInfo('getuiAliasGet:' + res.code);
							}
						})
						.catch((e) => {
							console.log('getuiAliasGet:catch' + e);
						});
				}
			} else {
				service.saveLogInfo(this.$t('joolun-pro-app.app.2k4b77'));
				console.log(this.$t('joolun-pro-app.app.f7l88p'));
			}
		},
		initUniCid() {
			// 个推cid
			service.saveLogInfo('-----initUniCid-----');
			// #ifdef APP-PLUS
			// 延迟获取
			setTimeout(() => {
				plus.push.getClientInfoAsync((info) => {
					let cid = info['clientid'];
					if (cid) {
						getApp().globalData.uniAppClientId = cid;
						getApp().getuiAliasBind();
						service.saveLogInfo('-----cid-----' + cid);
					}
				});
			}, 1000);
			// #endif
		},
		/**
		 * 初始化国际化语言设置
		 */
		initI18n() {
			// 如果之前设置过国际化语言, 那么自动显示上一次国际化语言
			let langCode = uni.getStorageSync('applicationLocale');
			if (langCode) {
				uni.setLocale(langCode);
				this.$i18n.locale = langCode;
			}
			// #ifdef MP
			// 小程序tabbar国际化
			uni.setTabBarItem({
				index: 0,
				text: this.$t('tabbar.tab1')
			});
			uni.setTabBarItem({
				index: 1,
				text: this.$t('tabbar.tab2')
			});
			uni.setTabBarItem({
				index: 2,
				text: this.$t('tabbar.tab3')
			});
			// #endif
		}
	}
};
</script>

<style lang="scss">

/* #ifndef APP-PLUS-NVUE  */
@import 'public/colorui/main.css';
@import 'public/colorui/icon.css';

.nav-list {
	display: flex;
	flex-wrap: wrap;
	padding: 0px 40upx 0px;
	justify-content: space-between;
}

.nav-li {
	padding: 30upx;
	border-radius: 12upx;
	width: 45%;
	margin: 0 2.5% 40upx;
	background-image: url(https://cdn.nlark.com/yuque/0/2019/png/280374/1552996358352-assets/web-upload/cc3b1807-c684-4b83-8f80-80e5b8a6b975.png);
	background-size: cover;
	background-position: center;
	position: relative;
	z-index: 1;
}

.nav-li::after {
	content: '';
	position: absolute;
	z-index: -1;
	background-color: inherit;
	width: 100%;
	height: 100%;
	left: 0;
	bottom: -10%;
	border-radius: 10upx;
	opacity: 0.2;
	transform: scale(0.9, 0.9);
}

.nav-li.cur {
	color: #fff;
	background: rgb(94, 185, 94);
	box-shadow: 4upx 4upx 6upx rgba(94, 185, 94, 0.4);
}

.nav-title {
	font-size: 32upx;
	font-weight: 300;
}

.nav-title::first-letter {
	font-size: 40upx;
	margin-right: 4upx;
}

.nav-name {
	font-size: 28upx;
	text-transform: Capitalize;
	margin-top: 20upx;
	position: relative;
}

.nav-name::before {
	content: '';
	position: absolute;
	display: block;
	width: 40upx;
	height: 6upx;
	background: #fff;
	bottom: 0;
	right: 0;
	opacity: 0.5;
}

.nav-name::after {
	content: '';
	position: absolute;
	display: block;
	width: 100upx;
	height: 1px;
	background: #fff;
	bottom: 0;
	right: 40upx;
	opacity: 0.3;
}

.nav-name::first-letter {
	font-weight: bold;
	font-size: 36upx;
	margin-right: 1px;
}

.nav-li text {
	position: absolute;
	right: 30upx;
	top: 30upx;
	font-size: 52upx;
	width: 60upx;
	height: 60upx;
	text-align: center;
	line-height: 60upx;
}

.text-light {
	font-weight: 300;
}

@keyframes show {
	0% {
		transform: translateY(-50px);
	}

	60% {
		transform: translateY(40upx);
	}

	100% {
		transform: translateY(0px);
	}
}

@-webkit-keyframes show {
	0% {
		transform: translateY(-50px);
	}

	60% {
		transform: translateY(40upx);
	}

	100% {
		transform: translateY(0px);
	}
}
/* #endif  */

.bg-scarlet {
  background-color: #f42121;
  color: #ffffff;
}

.text-scarlet {
  color: #f42121;
}

</style>
